from obs import ObsClient
from obs import PutObjectHeader
import os
import traceback
from cassandra.cluster import Cluster
import json


# 连接到本地Cassandra节点
cluster = Cluster(['172.17.0.2'])
session = cluster.connect()


# 创建或选择Keyspace（数据库）
session.execute("CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1}")
session.set_keyspace('mykeyspace')


# 创建表
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
    user_id UUID PRIMARY KEY,
    username TEXT,
    email TEXT
)
"""

session.execute(create_table_query)


# 插入数据
insert_data_query = """
INSERT INTO users (user_id, username, email) VALUES (uuid(), 'john_doe', 'john@example.com')
"""

session.execute(insert_data_query)

# 查询数据
select_data_query = "SELECT * FROM users"
result = session.execute(select_data_query)
data_list = []

for row in result:
    print(row.user_id, row.username, row.email)
    data_dict={'username':row.username,'email':row.email}
    data_list.append(data_dict)
json_data=json.dumps(data_list)
with open('temp.json','w') as f:
  f.write(json_data)
    
    

#上传至OBS
ak = "S36MA04XRYNBROTSS850"
sk = "xDg2BvMIfaSVnB7ymV0gGhM40lLKuLindQLsZaV2"
server = "https://obs.cn-north-4.myhuaweicloud.com"
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)

try:
    # 上传对象的附加头域
    headers = PutObjectHeader()
    # 【可选】待上传对象的MIME类型
    #headers.contentType = 'text/plain'
    bucketName = "hybbucket"
    # 对象名，即上传后的文件名
    objectKey = "temp.json"
    # 待上传文件的完整路径，如aa/bb.txt
    file_path = 'temp.json'
    # 上传文件的自定义元数据
    resp = obsClient.putFile(bucketName, objectKey, file_path)
    # 返回码为2xx时，接口调用成功，否则接口调用失败
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        print('etag:', resp.body.etag)
        print('versionId:', resp.body.versionId)
        print('storageClass:', resp.body.storageClass)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Put File Failed')
    print(traceback.format_exc())
